package com.leyou.user.service;

import com.leyou.common.util.CodecUtils;
import com.leyou.common.util.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author shkstart
 * @create 2020-05-08 19:38
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public Boolean checkData(String data, Integer type) {
        User record = new User();

        //根据前台穿的type值来判断是用户名还是手机号
        switch (type) {
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                return null;
        }
        return this.userMapper.selectCount(record) == 0;
    }

    public void send(String phone) {
        //生成验证码
        String code = NumberUtils.generateCode(6);

        redisTemplate.opsForValue().set("user:code:phone"+phone,code,5, TimeUnit.MINUTES);

        //1.发送电话和验证码
        Map<String,String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        //发送信息
        amqpTemplate.convertAndSend("sms.verify.code",map);

    }

    public Boolean register(User user,String codeu) {
        //获取验证码  判断验证码是否还在存活期限
        String code = redisTemplate.opsForValue().get("user:code:phone" + user.getPhone());
        if (codeu.equals(code)){

            //生成盐
            String salt = CodecUtils.generateSalt();
            user.setSalt(salt);
            //生成加密的密码
            String password = user.getPassword();
            String pass = CodecUtils.md5Hex(password, salt);
            user.setPassword(pass);

            user.setCreated(new Date());

            userMapper.insertSelective(user);
            return  true;
        }
        return false;
    }

    public User queryUser(User user) {

        //通过用户名查询到user对象  获取它的盐salt
        User user2 = new User();
        user2.setUsername(user.getUsername());
        User user3 = userMapper.selectOne(user2);

        if (user3 == null){
            return null;
        }

        //获取加密的密码
        String password = user.getPassword();
        String pass = CodecUtils.md5Hex(password, user3.getSalt());

        //根据加密后的密码和查询的密码进行比较
        if (!pass.equals(user3.getPassword())){
            return null;
        }
        return user3;
    }
}
